<script setup lang="ts">
import { getCart, updateNum } from '../../api/cart'
import { useUserStore } from '../../stores/user';
import { ref } from 'vue';
import type { Ref } from 'vue'
import { iPro } from '../../utils/homeType';
import { showToast } from 'vant';
const user = useUserStore()

const proList: Ref<iPro[]> = ref([])

getCart({
  userid: user.userid
}).then(res => {
  proList.value = res.data.data;
})

// 更新购物车数量的方法
function updateNumClick(type: string, item: iPro) {
  if (type == '10001') {
    // 减少
    // 如果 item.num 大于 1 就减一，否则就等于 1
    item.num = item.num > 1 ? item.num - 1 : 1
  } else if (type == '10002') {
    // 增加
    item.num++
  }

  updateNum({
    cartid: item.cartid,
    num: item.num
  }).then(res => {
    // console.log(res);
    showToast(res.data.message)
  })
}
</script>
<template>
  <div class="box">
    <header class="header"> 购物车 </header>
    <div class="content">

      <van-card v-for="item in proList" :key="item.proid" :num="item.num" :price="item.originprice" :title="item.proname">

        <template #thumb>
          <div class="imgBox">
            <van-checkbox class="img-checkbox" v-model="item.flag"></van-checkbox>
            <van-image width="50" height="50" :src="item.img1"></van-image>
          </div>
        </template>

        <template #footer>
          <van-button class="changeBtn" @click="updateNumClick('10001', item)" size="mini">-</van-button>
          <van-button class="changeBtn" @click="updateNumClick('10002', item)" size="mini">+</van-button>
        </template>
      </van-card>

    </div>
  </div>
</template>
<style scoped lang="scss">
.changeBtn {
  padding: 0 10px;
}

.imgBox {
  display: flex;
  flex-direction: row;
  align-items: center;

  .img-checkbox {
    padding-right: 15px;
  }
}
</style>
